<?php
class UserModule
{
	function index() {
	}
	function login() {
		global $_G;
		if($_G['uid']>0) {
			if(strpos($_G['gourl'],'login') != false || empty($_G['gourl'])) {
				$_G['gourl'] = url('home.php');
			}
			error(l('your_had_login','user'),$_G['gourl']);
		}
		if(!IS_POST) {
			include template('user_login') ;
		}else{
			$username = trim($_POST['username']);
			$password = trim($_POST['password']);
			$remember = 0;
			isset($_POST['remember'] ) && $_POST['remember']== 'on' && $remember = 1;
			!$username && error(l('needed_username','user'));
			!$password && error(l('needed_password','user'));
			if ( get_config('login_vdcode','user') ) {
				session_start();
				if ( strtolower(trim($_POST['vdcode'])) != $_SESSION['vdcode'] ) {
					unset($_SESSION['vdcode']);
					error(l('vdcode_error','user'));
				}
			}
			$status = $_G['userobj']->login($username,$password,$remember);
			switch ($status) {
				case 1:
					go($_G['gourl']);
					break;
				case -1:
				case -2:
					error(l('username_or_password_error','user'));
					break;
				case -3:
					error(l('user_is_blocked','user').'<div ><a href="register.php?step=2">'.l('click_here_to_active','user').'</a></div>','','',false);			
			}
		}
	}
	function regist() {
		global $_G;
		if($_G['uid']>0 && !isset($_GET['step'])) {
			error(l('your_had_regist','user'));
		}
		if(isset($_GET['step']) && $_GET['step'] == 2 && (!getGP('active_account','c') || (TIMESTAMP-getGP('active_account','c') > 600) )) {
			$this->sendmail();
		}
		if(!IS_POST) {
			$vid = getGP('vid','G','int');
			$code = getGP('code');
			if($vid){
				set_cookie('inviteid',$vid,3600);
			}else if($code){
				$vid = $_G['db']->result("SELECT vid FROM".table('user_invite')."WHERE code='".$code." AND expire < ".TIMESTAMP);
				if(!$vid){
					error(l('invitecode_is_invalid','user'));
				}
				set_cookie('inviteid',$vid,3600);
			}
			include template('user_regist') ;
		} else {
			$username = trim($_POST['username']);
			$password = trim($_POST['password']);
			$repassword = trim($_POST['repassword']);
			$email = trim($_POST['email']);
			if(strlen($username)<3 || strlen($username)>22) {
				error(Lang::get('needed_username_length','user'));
			}
			if(!$password) {
				error(Lang::get('needed_regist_password','user'));
			}
			if($password != $repassword) {
				error(Lang::get('needed_repassword','user'));
			}
			if(!is_email($email)) {
				error(Lang::get('needed_email','user'));
			}
			!isset($_POST['agree']) && error(Lang::get('needed_agreement','user'));
			if ( get_config('login_vdcode','user')) {
				session_start();
				if ( strtolower(trim($_POST['vdcode'])) != $_SESSION['vdcode'] ) {
					unset($_SESSION['vdcode']);
					error(l('vdcode_error','user'));
				}
			}
			if ($this->user_is_exist($username)) {
		    	error(Lang::get('user_is_exist','user'));
    		}
			if ($this->email_is_exist($email)) {
		    	error(Lang::get('email_is_exist','user'));
    		}
    		$user=$_G['userobj']->user_save('',array('password'=>$password,'username'=>$username,'email'=>$email));
    		if($user['uid']) {
    			$_G['userobj']->login($username,$password,true);
    			set_cookie('active_account',TIMESTAMP-700,3600);
    			if(getGP('inviteid','c')){
    				$_G['db']->update("user_intive",array('regtime'=>TIMESTAMP,'status'=>1,'touid'=>$user['uid']),array('vid'=>getGP('inviteid','c')));
    			}
    			
    			go('register.php?step=2');
    		}
		}
	}
	function lostpass() {
		global $_G;
		if(!IS_POST) {
			include template('user_lostpassword.tpl.php') ;
		} else {
			$username = trim($_POST['username']);
			$email = trim($_POST['email']);
			if(strlen($username)<3 || strlen($username)>22) {
				error(Lang::get('needed_username_length','user'));
			}
			if(!is_email($email)) {
				error(Lang::get('needed_email','user'));
			}
			if(!$this->user_lost_pass($username,$email)) {
				error(Lang::get('user_is_noexist','user'));
			}else{
				mail();
			}
		}
	}
	function logout() {
		global $_G;
		$_G['userobj']->logout();
		go();
	}
	function user_lost_pass($name,$email) {
		global $_G;
		$mail  = $_G['db']->result("SELECT email FROM ".DB_PREFIX."users WHERE username = LOWER('$name') AND email = LOWER('$mail') ");
		return $mail;
	}
	function user_is_exist($name) {
		global $_G;
		$name  = $_G['db']->result("SELECT username FROM ".DB_PREFIX."users WHERE username = LOWER('$name')");
		return $name;
	}
	function email_is_exist($mail) {
		global $_G;
		$mail  = $_G['db']->result("SELECT email FROM ".DB_PREFIX."users WHERE email = LOWER('$mail')");
		return $mail;
	}
	function user_is_blocked($name) {
		global $_G;
  		$deny  = $_G['db']->fetch('users','username', array('status' => 0,'username' => strtolower($name)) );
  		return $deny;
	}
	function sendmail($type='active',$content=null) {
		global $_G;
		$ajax=false;
		if(isset($_G['ajax'])){$ajax=true;}
		switch($type) {
			case 'active':
				if(!$_G['uid'] && (isset($_POST['mail']) && !is_email($_POST['mail'])) && (getGP('active_account','c') && (TIMESTAMP-getGP('active_account','c') < 600))){
					if($ajax){
						echo -1;exit;
					}else{
						error(l('no_login_or_invalid_email','user'));
					}
				}
				if(isset($_POST['mail']) && is_email($_POST['mail'])){
					$users = $_G['db']->fetch('users','*',array('email'=>$_POST['mail']));
				}else{
					$users = $_G['users'];
				}
				if(!isset($users['uid']) || !$users['uid']){
					if($ajax){
						echo -1;exit;
					}else{
						error(l('no_login_or_invalid_email','user'));
					}
				}
				if($users['status']) {
					if($ajax){
						echo 2;exit;
					}
					if($users['uid'] < 1) {
						go(url('login.php'));
					}else{
						echo 4;exit;
					}
				}
				$token = array('@username' => $users['username'],'@uid' => $users['uid'], '@activeurl'=>url($_G['settings']['siteurl'].'/register.php?f=active_account&uid='.$users['uid'].'&k='.base64_encode(TIMESTAMP)));
				$toemail = $users['email']?$users['email']:$_POST['mail'];
				$status = sendmail($toemail,get_email($type,'title'),get_email($type,'body',$token));
				if($status){
					set_cookie('active_account',TIMESTAMP,3600);
				}
				if($ajax){
					echo $status;exit;
				}else{
					return $status;
				}
				break;
			case 'password':
				$status = sendmail($toemail,get_email($type,'title'),get_email($type,'body',$token));
				break;	
			case 'username':
				break;	
		}
	}
	function forget_name(){
		global $_G;
		if(!IS_POST) {
			include template('user_forget') ;
		}else{
			$mail = $_POST['mail'];
			if(!is_email($mail)){
				error(l('needed_email','user'));
			}
			if(getGP('fotget_username','c') && (TIMESTAMP-getGP('fotget_username','c'))<600 ){
				error(l('try_after_ten_min','user'));
			}
			$user = $_G['userobj']->user_load(array('email'=>$mail));
			if(!$user['uid']) {
				error(l('email_no_exists','user'));
			}
			$token = array('@loginurl'=>url($_G['settings']['siteurl'].'/login.php'),'@username'=>$user['username']);
			$status = sendmail($mail,get_email('username','title'),get_email('username','body',$token));
			if($status) {
				set_cookie('fotget_username',TIMESTAMP,3600);
				error(l('fotget_username_mail_success','user'));
			}else{
				error(l('fotget_username_mail_false','user'));
			}	
		}
	}
	function forget_pass(){
		global $_G;
		if(!IS_POST) {
			include template('user_forget') ;
		}else{
			$name = $_POST['name'];
			$mail = $_POST['mail'];
			if(!is_email($mail)){
				error(l('needed_email','user'));
			}
			if(getGP('fotget_pass','c') && (TIMESTAMP-getGP('fotget_pass','c'))<600 ){
				error(l('try_after_ten_min','user'));
			}
			$user = $_G['userobj']->user_load(array('email'=>$mail,'username'=>$name));
			if(!$user['uid']) {
				error(l('user_is_noexist','user'));
			}
			$token = array('@loginurl'=>url($_G['settings']['siteurl'].'/login.php'),'@username'=>$user['username'],'@activeurl'=>url($_G['settings']['siteurl'].'/register.php?f=reset_pass&uid='.$user['uid'].'&k='.base64_encode(TIMESTAMP.md5($user['authkey']))));
			$status = sendmail($mail,get_email('password','title'),get_email('password','body',$token));
			if($status) {
				set_cookie('fotget_pass',TIMESTAMP,3600);
				error(l('fotget_pass_mail_success','user'));
			}else{
				error(l('send_mail_false','user'));
			}	
		}
	}
	function reset_pass(){
		$uid=$_GET['uid'];
		$k = $_GET['k'];
		if(!$uid || !$k){
			error(l('invalid_request'),url('index.php'));
		}
		$k = base64_decode(trim($k));
		$time = substr($k,0,10);
		if(TIMESTAMP-intval($time)>86400*2){
			error(l('invalid_request'),'index.php');
		}
		global $_G;
		$user = $_G['userobj']->get_user_byid($uid);
		if(!$user){
			error(l('user_is_noexist'),'index.php');
		}
		if(md5($user['authkey'])!=substr($k,10)) {
			error(l('invalid_request'),'index.php');
		}
		$auth = authcode("$user[uid]\t".md5($user['password']));
		$expire = 86400 * 30 ;
		set_cookie('auth', $auth, $expire);
		set_cookie('resetpass', TIMESTAMP, 600);
		goto_page(url('home.php?f=profile&a=password&t=reset'));
	}
	function active_mail(){
		global $_G;
		if(!IS_POST) {
			include template('user_forget') ;
		}else{
			$mail = $_POST['mail'];
			if(!is_email($mail)){
				error(l('needed_email','user'));
			}
			if(getGP('active_account','c') && (TIMESTAMP-getGP('active_account','c'))<600 ){
				error(l('try_after_ten_min','user'));
			}
			$status = $this->sendmail();
			if($status) {
				go('register.php?step=2');
			}else{
				error(l('send_mail_false','user'));
			}
		}
	}
	function ajax_active_mail(){
		global $_G;
		if(!$_G['uid']) {
			exit('0');
		}else{
			if(getGP('active_account','c') && (TIMESTAMP-getGP('active_account','c'))<600 ){
				exit('2');
			}
			$status = $this->sendmail();
			if($status) {
				exit('1');
			}else{
				exit('3');
			}
		}
	}
	function active_account() {
		global $_G;
		$uid = $_GET['uid'];
		$key = $_GET['k'];
		if(TIMESTAMP-base64_decode($key) > 48*3600){
			error(l('outof_active_time','user'));
		}
		if(!$uid) {
			error(l('invalid_request'));
		}
		$users = $_G['userobj']->get_user_byid($uid);
		if(!$users){
			error(l('user_is_noexist','user'));
		}
		if($users['status'] || $_G['db']->update('users',array('status'=>1),array('uid'=>$users['uid']))){
			$_G['db']->update('user_invite',array('status'=>2,'activetime'=>TIMESTAMP),array('touid'=>$users['uid']));
			$iuid=$_G['db']->result("SELECT uid FROM".table('user_invite')."WHERE touid=".$users['uid']);
			if($iuid)
			$_G['db']->update('user_stat',array('invites'=>'invites+1'),array('uid'=>$iuid));
			point('inviteuser',array('uid'=>$iuid,'relatedid '=>$users['uid']));
			go('register.php?step=3');
		}else{
			error(l('error_message'));
		}
	}
	function invite(){
		global $_G;
		$uid = getGP('vid','int');
		$code = getGP('code');
		if($uid){
			set_cookie('inviteuid',$uid,3600);
		}
		header('');
	}
	
}